package com.example.mybatisdemo.utils;

import com.example.core.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
public class SnUtils {
    @Autowired
    RedisUtil redisUtil;

    private final String ID_SEQUENCE_KEY = "id_sequence";
    private final long MAX_ID = 99999;// 如果当日业务订单大于这个数量，则会导致订单重复

    /**
     * 生成业务订单号
     *
     * @param code 业务代码
     * @return 订单号
     */
    public String buildSn(BusinessCode code) {
        return buildSn(code, 12);
    }

    public String buildSn(BusinessCode code, int length) {
        LocalDate date = LocalDate.now();
        String orderSn = String.format("%d%02d%02d%02d",
                code.value,             //长度1
                date.getYear(),         //长度4
                date.getMonthValue(),   //长度2
                date.getDayOfMonth()    //长度2
        );
        int sLen = length - orderSn.length();

        orderSn += String.format("%0" + sLen + "d", getLatestId());
        return orderSn;
    }

    private long getLatestId() {
        Long latestId = redisUtil.increment(ID_SEQUENCE_KEY);
        if (latestId >= MAX_ID) {
            redisUtil.remove(ID_SEQUENCE_KEY);
        }
        return latestId;
    }

    // 业务编号
    public enum BusinessCode {
        SHOPPING_ORDER(1);

        int value;

        BusinessCode(int index) {
            this.value = index;
        }
    }
}
